import Vue from 'vue'
import { http } from './http'

class Auth {
  constructor  () {
    this.rulelist = []
    this.loading = true
  }


  /**
   * 校验是否有权限
   * @param {array} node
   * @returns {boolean}
   */
  chkAuth (node) {
    if (Array.isArray(node)) {
      this.rulelist.map((item, idx) => {
        console.log(item, idx)
      })
    }
    const idx = this.rulelist.indexOf(node)
    return idx !== -1
  }


  /**
   * 登录
   * @param {string} username
   * @param {string} password
   * @returns {Promise<any>}
   */
  login (username, password) {
    return new Promise((resolve, reject) => {
      http.post('admin/login', {
        username,
        password
      })
        .then(result => {
          if (result.code) {
            reject(new Error(result.error))
          } else {
            this.loading = false
            this.rulelist = result.rules
            localStorage.setItem('access_token', result.access_token)
            localStorage.setItem('access_expire', result.expire_in + (new Date().getTime() / 1000))
            resolve()
          }
        })
        .catch(reject)
    })
  }

}

export const auth = new Auth

Vue.prototype.$auth = auth
